const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//格式化货币
var numberUtil = {
  numberFormat: function (value) {
    var num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
      num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    var cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
      cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);  
  }
}

//封装带header的POST网络请求
var wxPOST = {
  POSTHTTP: function (url, data) {
    var promise = new Promise((resolve, reject) => {
      var that = this;
      var postData = data;
      //网络请求
      wx.request({
        url: url,
        data: postData,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'sessionId': getApp().globalData.sessionId
        },
        success: function (res) {
          //服务器返回数据
          if (res.data.code != 1000) {
            resolve(res);
          } else {
            //返回错误提示信息
            reject(res);
          }
        },
        error: function (e) {
          reject('网络出错');
        }
      })
    });
    return promise;
  }
}

//封装带header的GET网络请求
var wxGET ={
  GETHTTP: function (url, data) {
    var promise = new Promise((resolve, reject) => {
      var that = this;
      var postData = data;
      //网络请求
      wx.request({
        url: url,
        data: postData,
        method: 'GET',
        header: { 
          'content-type': 'application/json',
          'sessionId': getApp().globalData.sessionId
          },
        success: function (res) {
          //服务器返回数据
          if (res.data.code != 1000) {
            resolve(res);
          } else {
            //返回错误提示信息
            reject(res);
          }
        },
        error: function (e) {
          reject('网络出错');
        }
      })
    });
    return promise;
  }
}

module.exports = {
  formatTime: formatTime,
  numberFormat: numberUtil.numberFormat,
  gethttp: wxGET.GETHTTP,
  posthttp: wxPOST.POSTHTTP
}
